package com.jihox.abookpro;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Paint.Style;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jihox.abookpro.curl.CurlPage;
import com.jihox.abookpro.curl.CurlRenderer;
import com.jihox.abookpro.curl.CurlView;
import com.jihox.abookpro.curl.CurlView.EditCaptionTextViewClickable;
import com.jihox.abookpro.curl.CurlView.GoToChangeCaption;
import com.jihox.abookpro.curl.CurlView.GoToChangePicture;
import com.jihox.abookpro.domain.BookProject;
import com.jihox.abookpro.domain.Caption;
import com.jihox.abookpro.domain.Page;
import com.jihox.abookpro.domain.PagePicture;
import com.jihox.abookpro.fragment.AssertFragment;
import com.jihox.abookpro.util.AndroidImageFile;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.util.DensityUtil;
import com.jihox.abookpro.util.DynamicBlockingQueue;
import com.jihox.abookpro.util.NativeImageLoader;
import com.jihox.abookpro.util.PictureUtil;
import com.jihox.abookpro.view.ImageCenterButton;
import com.jihox.abookpro.view.ZoomImageView;

/**
 * Simple Activity for curl testing.
 * 
 */
public class CurlActivity extends BaseActivity {

	private CurlView mCurlView;
	private RelativeLayout layoutRoot;
	public BookProject bookProject;
	//拷贝BookProject，退出编辑状态时用
	//public BookProject bookProjectCopy;
	public static float innerPageScreenAndRealRatio = 0f;
	public static float coverPageScreenAndRealRatio = 0f;
	private static int EDIE_SINGLE_PAGE = 0x100002;
	private int currentIndex = 0;
	private float curlViewMarginTop = 0.24f;// TODO:Define in XML
	private float curlViewMarginBottom = .11f;
	private float curlViewMarginLeftOrRight = -1f;
	private final int addCaptionRequestCode = 1000;
	private ImagesObserver imagesObserver;
	private boolean isFirstSDRemind = true;
	private boolean changedSizeForPhotoBook = false;
	private boolean changedSizeForCalendar = false;
	private Button editCaptionButton;
	private Button editSubCaptionButton;
	// 判断是否是来自accountDetailActivity
	private String from = null;

	private int mPageNum = -1;
	private int mPictureNum = -1;
	
	public static String templateName = "";
	
	private boolean isEditState = false;
	private boolean isCurlNeedAssert;
	
	private Button returnButton;
	private Button nextStep;
	private Button saveButton;
	
	private ImageCenterButton adjustButton;
	private LinearLayout bottomLayout;
	private ImageCenterButton editButton;
	private TextView titleText;
	
	private AssertFragment assertFragment;
	public static int imageWidth = 0;
	public static int imageHeight = 0;
	private final int addPAgeRequestCode = 0X02;
	private Typeface typeface;
	private PageProvider pageProvider;
	protected ArrayList<ZoomImageView> zoomViewList;
	
	private BookProject orignal_project = null;
	 
	
	private Handler fileHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case 1:
				Toast.makeText(CurlActivity.this, 
						getResources().getString(R.string.T_File_Not_Found_Error),Toast.LENGTH_SHORT).show();
				break;
			case 2:
				 Toast.makeText(CurlActivity.this,
		                 getResources().getString(R.string.T_No_SDCard), Toast.LENGTH_SHORT).show();
				 break;
			case 3:
				 Toast.makeText(CurlActivity.this,
		                 getResources().getString(R.string.T_Read_Template_Error), Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		imageHeight = 0;
		imageWidth = 0;
		SharedPreferences preferences = getSharedPreferences(
				"assert_pref", Context.MODE_APPEND);
		isCurlNeedAssert = preferences.getBoolean("isCurlNeedAssert", true);
		templateName = this.getIntent().getStringExtra("templateName");
		Bundle bundle = this.getIntent().getExtras();
		if(null != savedInstanceState){
			MyApplication.getInstance().setBookProject( (BookProject) savedInstanceState.getSerializable("bookproject"));
			bookProject = MyApplication.getInstance().getBookProject();
			// 给selectedphotolist添加选择的照片，以便点击返回时调用
			ShowImageActivity.selectedPhotoList.clear();
			for (Page currentPage : bookProject.getBook().getPages()) {
				if (currentPage.getPictures() != null
						&& currentPage.getPictures().size() > 0) {
					for (PagePicture pagePicture : currentPage
							.getPictures()) {
						if (!pagePicture.isClipart()) {
							String path = pagePicture.getImage().getPath();
							File file = new File(path);
							AndroidImageFile selectedFile = new AndroidImageFile();
							selectedFile.setPath(path);
							selectedFile.setFolderName(file.getParent());
							ShowImageActivity.selectedPhotoList
									.add(selectedFile);
						}
					}
				}
			}		
		}else{
			MyApplication application = MyApplication.getInstance();
			bookProject = application.getBookProject();
		}
		if (templateName==null){
			templateName = bookProject.getBook().getTemplateName();
		}
		//备份原始bookproject
		try {
			orignal_project = (BookProject) bookProject.deepCopy();
		} catch (Exception e) {			
			e.printStackTrace();
		}
		if (bundle != null) {
			currentIndex = bundle.getInt("CurrentIndex");
			from = bundle.getString("From", null);
		}

		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		if (bookProject != null
				&& bookProject.getBook().getProduct().getCategory() == 2) {
			setContentView(R.layout.activity_curl_calendar);
			
		} else {
			setContentView(R.layout.activity_curl);
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
					
			titleText = (TextView) findViewById(R.id.title);
		}
		
		saveButton = (Button) findViewById(R.id.btnsave);
		saveButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (titleText!=null){
					titleText.setText(R.string.preview_title_photobook);
				}
				
				nextStep.setVisibility(View.VISIBLE);
				saveButton.setVisibility(View.INVISIBLE);
				bottomLayout.setVisibility(View.VISIBLE);
				if (editCaptionButton!=null){
					editCaptionButton.setVisibility(View.INVISIBLE);	
				}
				if (editSubCaptionButton!=null){
					editSubCaptionButton.setVisibility(View.INVISIBLE);	
				}
				
				int index = mCurlView.getCurrentIndex();
				isEditState = false;
				
				for (Page page:bookProject.getBook().getPages()){
					if (page.getCaptions() != null && page.getCaptions().size() > 0) {
						for (Caption caption : page.getCaptions()) {
							if (caption.isShowTempText()){
								caption.setShowTempText(false);
								caption.setText(caption.getTempText());
								caption.setTempText("");
							}
							
						}
					}
				}
				MyApplication.getInstance().setBookProject(bookProject);
				bookProject = MyApplication.getInstance().getBookProject();
				try {
					orignal_project = (BookProject) bookProject.deepCopy();
					for (Page page:orignal_project.getBook().getPages()){
						page.setNeedRedraw(false);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				mCurlView.setEditable(isEditState);
				mCurlView.releaseMemory();
				mCurlView.setCurrentIndex(index);
			}
		});
		editButton = (ImageCenterButton) findViewById(R.id.btn_edit);
		editButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (titleText!=null){
					titleText.setText(R.string.Edit_PhotoBook);
				}
				
				int index = mCurlView.getCurrentIndex();
				isEditState = true;
				if (editCaptionButton!=null){
					editCaptionButton.setVisibility(View.VISIBLE);
				}
				if (editSubCaptionButton!=null){
					editSubCaptionButton.setVisibility(View.VISIBLE);
				}
				
				saveButton.setVisibility(View.VISIBLE);
				nextStep.setVisibility(View.INVISIBLE);
				bottomLayout.setVisibility(View.INVISIBLE);
				mCurlView.setEditable(isEditState);
				mCurlView.setCurlStateNone();
				mCurlView.releaseMemory();
				mCurlView.setCurrentIndex(index);
				if(isEditState && isCurlNeedAssert){
					if(1<=index){
						List<Rect> captions =getCaptionRect(index*2-1);
						if (captions!=null && captions.size()>0){
							Rect rect = getCaptionRect(index*2+1).get(0);
							assertFragment=new AssertFragment(2, rect, 20,0);
							getFragmentManager().beginTransaction().add(R.id.rlCurl, assertFragment).commit();
							isCurlNeedAssert=false;
						}
					}
				}
			}
		});
		
		bottomLayout = (LinearLayout) findViewById(R.id.layout_bottom);

		if (bookProject ==null){
			finish();
		}
//		Bitmap bm = PictureUtil.getBitmapFromAssetsFile(
//				getApplicationContext(), "product-pid-"
//						+ bookProject.getBook().getProduct().getPid()
//						+ "/album_bg.png");
//		BitmapDrawable bd = new BitmapDrawable(this.getResources(), bm);
//		rlCurl.setBackgroundDrawable(bd);
		layoutRoot = (RelativeLayout)findViewById(R.id.rlCurl);
		mCurlView = (CurlView) findViewById(R.id.curl);
		if (bookProject != null
				&& bookProject.getBook().getProduct().getCategory() == 2) {
			mCurlView.setProductCategory(2);
		} else {
			adjustButton = (ImageCenterButton) findViewById(R.id.btn_adjust);
			adjustButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.setClass(CurlActivity.this, ChangeSequenceActivity.class);
					Bundle mBundle = new Bundle();
					mBundle.putInt("CurrentIndex", mCurlView.getCurrentIndex());
					intent.putExtras(mBundle);
					CurlActivity.this.startActivityForResult(intent, addPAgeRequestCode);
					
				}
			});
			mCurlView.setProductCategory(1);
			try {
				typeface = Typeface.createFromAsset(
						CurlActivity.this.getAssets(), "fonts/SourceHanSansCN-Normal.otf");
			} catch (Exception ex) {
			}
		}

		pageProvider = new PageProvider(this);
		mCurlView.setPageProvider(pageProvider);

		returnButton = (Button) findViewById(R.id.btnReturn);
		returnButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				reback();
			}
		});
		
		nextStep = (Button) findViewById(R.id.btnnext);
		nextStep.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {

				// 检查有照片丢失
				if (((MyApplication) view.getContext().getApplicationContext())
						.checkImageExist(bookProject) != null) {
					showLostDialog();
				} else {
					goToOrderActivity();
				}
			}

		});
		
		/**
		 * Button sequenceButton = (Button) findViewById(R.id.btnSequence);
		 * sequenceButton.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { Vector<Page> pages =
		 * bookProject.getBook().getPages(); Random random = new Random(); if
		 * (bookProject.getBook().getProduct().getCategory() == 1) { List<Page>
		 * list = new ArrayList<Page>(); // 非剪切画内页下标 List<Integer> pageIndex =
		 * new ArrayList<Integer>(); boolean isClipartPage = false; //
		 * 获得所有非剪切画内页 for (int i = 0; i < pages.size(); i++) { if
		 * (pages.get(i).getType() == Page.REGULAR) { List<PagePicture> pictures
		 * = pages.get(i) .getPictures(); for (PagePicture pagePicture :
		 * pictures) { if (!pagePicture.isClipart()) { isClipartPage = true;
		 * break; } } if (isClipartPage) { list.add(pages.get(i));
		 * pageIndex.add(i); isClipartPage = false; } } } for (int i = 0; i <
		 * pageIndex.size(); i++) { int temp = random.nextInt(list.size());
		 * pages.set(pageIndex.get(i), list.get(temp)); list.remove(temp); }
		 * pageIndex.clear(); } else if
		 * (bookProject.getBook().getProduct().getCategory() == 2) { //
		 * 所有页中非剪切画图片 List<PagePicture> notClipartPictures = new
		 * ArrayList<PagePicture>(); // 非剪切画下标 List<Integer> pictureIndex = new
		 * ArrayList<Integer>(); for (Page page : pages) { // 每页中的所有图片
		 * List<PagePicture> pagePictures = page.getPictures(); for (int i = 0;
		 * i < pagePictures.size(); i++) { if (!pagePictures.get(i).isClipart())
		 * { notClipartPictures.add(pagePictures.get(i)); } } } for (Page page :
		 * pages) { // 每页中的所有图片 List<PagePicture> pagePictures =
		 * page.getPictures(); for (int i = 0; i < pagePictures.size(); i++) {
		 * if (!pagePictures.get(i).isClipart()) { int temp =
		 * random.nextInt(notClipartPictures .size()); pagePictures.set(i,
		 * notClipartPictures.get(temp)); notClipartPictures.remove(temp); } }
		 * page.setPictures(pagePictures); } mCurlView.releaseMemory(); } //
		 * 重新设置bookProject，然后跳转到当前Activity
		 * bookProject.getBook().setPages(pages); Intent intent = new Intent();
		 * Bundle bundle = new Bundle(); intent.setClass(CurlActivity.this,
		 * CurlActivity.class); bundle.putSerializable("BookProject",
		 * bookProject); bundle.putInt("pixelsOfPicture", pixelsOfPicture);
		 * intent.putExtras(bundle); recycleBitmaps();
		 * NativeImageLoader.getInstance().clearCache();
		 * CurlActivity.this.startActivity(intent); finish(); } });
		 */
		
		if (getLastNonConfigurationInstance() != null) {
			currentIndex = (Integer) getLastNonConfigurationInstance();
		}
		loadImageProgressBar();

		mCurlView.setSizeChangedObserver(new SizeChangedObserver());
		
		if (bookProject.getBook().getProduct().getCategory() == 1) {
			editCaptionButton = (Button) findViewById(R.id.edit_caption_button);
			editSubCaptionButton = (Button) findViewById(R.id.edit_caption_button_sub);
			editCaptionButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (mCurlView.getCurrentIndex()>0){
						return;
					}
					goToAddCaption(mCurlView.getCurrentIndex(), 0,
							addCaptionRequestCode);// caption里应该加一个标识具体caption的字段，这里按照1.xml里定义的顺序，将0视为标题，1为副标题
				}
			});
			editSubCaptionButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (mCurlView.getCurrentIndex()>0){
						return;
					}
					goToAddCaption(mCurlView.getCurrentIndex(), 1,
							addCaptionRequestCode);
				}
			});
			if (currentIndex == 0) {
				editCaptionButton.setClickable(true);
				editSubCaptionButton.setClickable(true);
			} else if (currentIndex != 0) {
				editCaptionButton.setClickable(false);
				editSubCaptionButton.setClickable(false);
			}
		}

		if (bookProject.getBook().getProduct().getCategory() == 1) {
			mCurlView
					.setEditCaptionTextViewClickable(new EditCaptionTextViewClickable() {
						@Override
						public void updateClickable(int mCurrentIndex) {
							if(isEditState){
								if (mCurlView.getCurrentIndex() == 0) {
									editCaptionButton.setClickable(true);
									editSubCaptionButton.setClickable(true);
								} else {
									editCaptionButton.setClickable(false);
									editSubCaptionButton.setClickable(false);
								}
								if(isCurlNeedAssert){
									if(1<=mCurrentIndex){
										List<Rect> captions = getCaptionRect(mCurrentIndex*2-1);
										if (captions!=null && captions.size()>0){
											Rect rect = captions.get(0);
											assertFragment=new AssertFragment(2, rect, 20,0);
											getFragmentManager().beginTransaction().add(R.id.rlCurl, assertFragment).commit();
											isCurlNeedAssert=false;
										}
									}
								}
							}
							
							/*
							 * if (mCurrentIndex > 0 && mCurrentIndex <
							 * bookProject.getBook() .getPages().size() / 2) {
							 * Vector<Page> pages = bookProject.getBook()
							 * .getPages(); boolean isClipartPage = true; if
							 * (pages.get(mCurrentIndex * 2 - 1).getType() ==
							 * Page.REGULAR) { List<PagePicture> pictures =
							 * pages.get( mCurrentIndex * 2 - 1) .getPictures();
							 * for (PagePicture pagePicture : pictures) { if
							 * (!pagePicture.isClipart()) { isClipartPage =
							 * false; break; } } if (!isClipartPage) {
							 * runOnUiThread(new Runnable() { public void run()
							 * { editPageCaptionButton
							 * .setVisibility(View.VISIBLE); } }); isClipartPage
							 * = true; } else { runOnUiThread(new Runnable() {
							 * public void run() { editPageCaptionButton
							 * .setVisibility(View.INVISIBLE); } }); } } if
							 * (pages.get(mCurrentIndex * 2).getType() ==
							 * Page.REGULAR) { List<PagePicture> pictures =
							 * pages.get( mCurrentIndex * 2).getPictures(); for
							 * (PagePicture pagePicture : pictures) { if
							 * (!pagePicture.isClipart()) { isClipartPage =
							 * false; break; } } if (!isClipartPage) {
							 * runOnUiThread(new Runnable() { public void run()
							 * { editSubPageCaptionButton
							 * .setVisibility(View.VISIBLE); } }); isClipartPage
							 * = true; } else { runOnUiThread(new Runnable() {
							 * public void run() { editSubPageCaptionButton
							 * .setVisibility(View.INVISIBLE); } }); } } }
							 */
						}
					});
		}

		imagesObserver = new ImagesObserver(new Handler()) {
			@Override
			public void onChange(boolean selfChange) {
				if (!checkSelectedList()) {
					onKeyDown(KeyEvent.KEYCODE_BACK, null);
				}
			}
		};
		this.getContentResolver().registerContentObserver(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true,
				imagesObserver);
		mCurlView.setGoToChangeCaption(new GoToChangeCaption() {
			
			@Override
			public void goToChangeCaption(int pageNum, int captionNum) {
				mPageNum =-1;
				mPictureNum = -1;
				mCurlView.releaseMemory();
				mCurlView.setFirstMoveFlag(true);
				mCurlView.setCurrentIndex( mCurlView.getCurrentIndex());
				goToAddCaption(pageNum, captionNum,addCaptionRequestCode);
			}
		});
		mCurlView.setGoToChangePicture(new GoToChangePicture() {
			
			@Override
			public void goToChangePicture(int pageNum, int pictureNum) {
//				Log.i("msg_picture_info", pageNum+"-------------"+pictureNum);
				mPageNum = pageNum;
				mPictureNum = pictureNum;
				mCurlView.releaseMemory();
				mCurlView.setFirstMoveFlag(true);
				mCurlView.setCurrentIndex( mCurlView.getCurrentIndex());

				Intent intent = new Intent(CurlActivity.this,SinglePageEditActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				intent.putExtra("mPageNum", mPageNum);
				intent.putExtra("mPictureNum", mPictureNum);
				intent.putExtra("mindex", mCurlView.getCurrentIndex());
				intent.putExtra("imageWidth", imageWidth);
				intent.putExtra("imageHeight", imageHeight);
				intent.putExtra("bookProject", bookProject);
				intent.putExtra("category", bookProject.getBook().getProduct().getCategory());
				startActivityForResult(intent, EDIE_SINGLE_PAGE);
				
			}
		});
		
		if(null != savedInstanceState){
			mCurlView.setEditable(isEditState);
			mCurlView.releaseMemory();
			mCurlView.setCurrentIndex(savedInstanceState.getInt("currentindex"));
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putSerializable("bookproject", bookProject);
		outState.putInt("currentindex", mCurlView.getCurrentIndex());
	}
	
	private void reback(){
		if(isEditState){
			if (titleText!=null){
				titleText.setText(R.string.preview_title_photobook);
			}
			
			bottomLayout.setVisibility(View.VISIBLE);
			saveButton.setVisibility(View.INVISIBLE);
			nextStep.setVisibility(View.VISIBLE);
			if (editCaptionButton!=null){
				editCaptionButton.setVisibility(View.INVISIBLE);
			}
			if (editSubCaptionButton!=null){
				editSubCaptionButton.setVisibility(View.INVISIBLE);
			}
			
			int index = mCurlView.getCurrentIndex();
			isEditState = false;		
			int pageIndex =0;
			for (Page page:bookProject.getBook().getPages()){
				if (page.getCaptions() != null && page.getCaptions().size() > 0) {
					for (Caption caption : page.getCaptions()) {
						if (caption.isShowTempText()){
							orignal_project.getBook().getPages().get(pageIndex).setNeedRedraw(true);
						}
						
					}
				}
				pageIndex++;
			}
		
			try {
				bookProject = (BookProject) orignal_project.deepCopy();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			MyApplication.getInstance().setBookProject(bookProject);
			
			mCurlView.setEditable(isEditState);
			mCurlView.releaseMemory();
			mCurlView.setCurrentIndex(index);
		}else {
			if (AccountDetailActivity.class.getName().equals(from)) {
				recycleBitmaps();
				NativeImageLoader.getInstance().clearCache();
				finish();
			} else {
				Intent intent = new Intent();
				intent.setClass(CurlActivity.this,
						GallerySelectActivity.class);
				intent.putExtra("templateName", templateName);
				Bundle mBundle = new Bundle();
				if (bookProject.getBook().getPages().get(0).getCaptions() != null
						&& bookProject.getBook().getPages().get(0)
								.getCaptions().size() > 0) {
					String[] captions = new String[bookProject.getBook()
							.getPages().get(0).getCaptions().size()];
					for (int i = 0; i < bookProject.getBook().getPages()
							.get(0).getCaptions().size(); i++) {
						captions[i] = bookProject.getBook().getPages()
								.get(0).getCaptions().get(i).getText();
					}
					mBundle.putStringArray("Captions", captions);
				}
				intent.putExtras(mBundle);

				recycleBitmaps();
				NativeImageLoader.getInstance().clearCache();
				finish();
				CurlActivity.this.startActivity(intent);
			}
		}
	}
		

	/**
	 * 提示照片丢失
	 */
	private void showLostDialog() {
		final Dialog dialog = new Dialog(this, R.style.JHDialog);
		// 设置它的ContentView
		dialog.setContentView(R.layout.dialog_general);
		Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
		Button buttonCancel = (Button) dialog
				.findViewById(R.id.dialog_button_cancel);
		TextView dialogTitle = (TextView) dialog
				.findViewById(R.id.dialog_title);
		TextView dialogMessage = (TextView) dialog
				.findViewById(R.id.dialog_message);

		buttonOK.setBackgroundResource(R.drawable.delete_style);
		buttonCancel.setBackgroundResource(R.drawable.green_style);
		buttonOK.setText(R.string.T_Ok);
		buttonCancel.setText(R.string.T_Cancel);
		dialogTitle.setText(R.string.T_Photo_Remind);
		dialogMessage.setText(R.string.T_Photo_Lost);

		buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				// 返回 GallerySelectActivity
				ShowImageActivity.selectedPhotoList.clear();
				for (Page currentPage : bookProject.getBook().getPages()) {
					if (currentPage.getPictures() != null
							&& currentPage.getPictures().size() > 0) {
						for (PagePicture pagePicture : currentPage
								.getPictures()) {
							if (!pagePicture.isClipart()) {
								String path = pagePicture.getImage().getPath();
								File file = new File(path);
								AndroidImageFile selectedFile = new AndroidImageFile();
								selectedFile.setPath(path);
								selectedFile.setFolderName(file.getParent());
								ShowImageActivity.selectedPhotoList
										.add(selectedFile);
							}
						}
					}
				}
				ShowImageActivity.showNextButton = false;
				Intent intent = new Intent();
				intent.putExtra("bookProduct", bookProject.getBook()
						.getProduct());
				intent.setClass(v.getContext(), GallerySelectActivity.class);
				intent.putExtra("templateName", templateName);
				Bundle mBundle = new Bundle();
				if (bookProject.getBook().getPages().get(0).getCaptions() != null
						&& bookProject.getBook().getPages().get(0)
								.getCaptions().size() > 0)
					mBundle.putString("Caption", bookProject.getBook()
							.getPages().get(0).getCaptions().get(0).getText());
				mBundle.putString("From", from);
				intent.putExtras(mBundle);
				v.getContext().startActivity(intent);
			}
		});
		buttonCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	private void goToAddCaption(int pageNum, int captionNum, int requestCode) {

		Intent intent = new Intent();
		intent.setClass(CurlActivity.this, ChangeCaptionActivity.class);
		Bundle mBundle = new Bundle();
		mBundle.putInt("CurrentIndex", mCurlView.getCurrentIndex());
		mBundle.putInt("PageNum", pageNum);
		mBundle.putInt("CaptionNum", captionNum);
		intent.putExtras(mBundle);
		CurlActivity.this.startActivityForResult(intent, requestCode);
	}

	public static String saveCoverBitmap(Context context, Bitmap coverBitmap,
			int compressQuatity,String fileName) {

		File f = new File(context.getCacheDir(), fileName);

		if (f.exists()) {
			f.delete();
		}
		try {
			FileOutputStream out = new FileOutputStream(f);
			coverBitmap.compress(Bitmap.CompressFormat.PNG, compressQuatity,
					out);
			out.flush();
			out.close();
			coverBitmap.recycle();
			coverBitmap = null;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return f.toString();
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent();
		intent.setClass(CurlActivity.this, GallerySelectActivity.class);
		intent.putExtra("templateName", templateName);
		Bundle mBundle = new Bundle();
		if (bookProject.getBook().getPages().get(0).getCaptions() != null
				&& bookProject.getBook().getPages().get(0).getCaptions().size() > 0) {
			String[] captions = new String[bookProject.getBook().getPages()
					.get(0).getCaptions().size()];
			for (int i = 0; i < bookProject.getBook().getPages().get(0)
					.getCaptions().size(); i++) {
				captions[i] = bookProject.getBook().getPages().get(0)
						.getCaptions().get(i).getText();
			}
			mBundle.putStringArray("Captions", captions);
		}
		intent.putExtras(mBundle);
		recycleBitmaps();
		finish();
		CurlActivity.this.startActivity(intent);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		getContentResolver().unregisterContentObserver(imagesObserver);
		mCurlView.onPause();
		mCurlView.releaseMemory();
		NativeImageLoader.getInstance().clearCache();
//		BitmapDrawable bd = (BitmapDrawable) rlCurl.getBackground();
//		rlCurl.setBackgroundResource(0);
//		bd.setCallback(null);
//		bd.getBitmap().recycle();
		System.gc();
		super.onDestroy();
	}

	private void goToOrderActivity() {
		//跳转到订单页面  设置全局
		MyApplication myApplication=MyApplication.getInstance();
		myApplication.setBookProject(bookProject);
	
		Intent intent = new Intent();
		intent.putExtra("templateName", templateName);
		intent.setClass(CurlActivity.this, OrderActivity.class);
		Bundle mBundle = new Bundle();

		Bitmap coverBitmap = NativeImageLoader.getInstance()
				.loadNativeImageSyncAndOriginal(getImagePath(0), false);
		coverBitmap = createCoverBitmap(CurlActivity.this, bookProject
				.getBook().getProduct().getCategory(), coverBitmap);
		mBundle.putString("coverBitmap",
				saveCoverBitmap(CurlActivity.this, coverBitmap, 10,"cover.png"));
		mBundle.putString("From", from);

		intent.putExtras(mBundle);
		CurlActivity.this.startActivity(intent);
		recycleBitmaps();
		NativeImageLoader.getInstance().clearCache();
		finish();
	}

	private Bitmap createCoverBitmap(Context context, int category,
			Bitmap thumbnail) {
		Bitmap resultBitmap = null;
		Bitmap srcBitmap = null;
		if (category==2){
			srcBitmap = PictureUtil.getBitmapFromAssetsFile(
					context.getApplicationContext(),  "listitem_cover_bg_calendar.png");
		}else{
			srcBitmap = PictureUtil.getBitmapFromAssetsFile(
					context.getApplicationContext(),  "listitem_cover_bg.png");
		}

		int srcW = srcBitmap.getWidth();
		int srcH = srcBitmap.getHeight();

		// 创建一个新的和SRC长度宽度一样的位图
		Paint paint = new Paint();
		paint.setAntiAlias(true);
		paint.setFlags(Paint.ANTI_ALIAS_FLAG);

		resultBitmap = Bitmap.createBitmap(srcW, srcH, Config.ARGB_4444);
		Canvas cv = new Canvas(resultBitmap);
		cv.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG
				| Paint.FILTER_BITMAP_FLAG));
		cv.drawBitmap(srcBitmap, 0, 0, null);// 在 0，0坐标开始画入srcshareImage
		cv.save();

		int coverW = thumbnail.getWidth();
		int coverH = thumbnail.getHeight();
		if (category == 2) {
			Matrix mMatrix = new Matrix();
			float[] array = new float[] { 17, 17, 17 + coverW, 17, 17 + coverW,
					17 + coverH, 17, 17 + coverH };
			mMatrix.setPolyToPoly(array, 0, new float[] { 17, 17, 132, 10, 145,
					114, 30, 125 }, 0, array.length >> 1);
			cv.concat(mMatrix);
			cv.drawBitmap(thumbnail, 17, 17, paint);
			
		} else {
			Matrix mMatrix = new Matrix();
			float[] srcP = new float[] { 17, 6, 17 + coverW, 6, 17 + coverW,
					6 + coverH, 17, 6 + coverH };
			float[] desP = new float[] { 17, 6, 120, 9, 120, 141, 17, 127 };
			mMatrix.setPolyToPoly(srcP, 0, desP, 0, srcP.length >> 1);
			cv.concat(mMatrix);
			cv.drawBitmap(thumbnail, 17, 6, paint);
		}
		cv.restore();// 存储
		srcBitmap.recycle();
		thumbnail.recycle();

		return resultBitmap;
	}

	private Bitmap front = null;
	private Bitmap back = null;
	private Bitmap dstbmp = null;

	private void recycleBitmaps() {

		if (front != null) {
			front.recycle();
		}
		if (back != null) {
			back.recycle();
		}
		if (dstbmp != null) {
			dstbmp.recycle();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& !AccountDetailActivity.class.getName().equals(from)) {
//			if(isCurlNeedAssert){
//				getFragmentManager().beginTransaction().remove(assertFragment).commit();
//				SharedPreferences preferences = this.getSharedPreferences(
//						"assert_pref", Context.MODE_APPEND);
//				Editor editor = preferences.edit();
//				editor.putBoolean("isCurlNeedAssert", false);
//				editor.commit();
//				isCurlNeedAssert=false;
//			}else {
//				Intent intent = new Intent();
//				intent.setClass(CurlActivity.this, GallerySelectActivity.class);
//				intent.putExtra("templateName", templateName);
//				Bundle mBundle = new Bundle();
//				if (bookProject.getBook().getPages().get(0).getCaptions() != null
//						&& bookProject.getBook().getPages().get(0).getCaptions()
//								.size() > 0)
//					mBundle.putString("Caption", bookProject.getBook().getPages()
//							.get(0).getCaptions().get(0).getText());
//				intent.putExtras(mBundle);
//				CurlActivity.this.startActivity(intent);
//				recycleBitmaps();
//				NativeImageLoader.getInstance().clearCache();
//				finish();
//			}
			reback();
		} else {
			recycleBitmaps();
			NativeImageLoader.getInstance().clearCache();
			finish();
		}
		return false;
	}

	@Override
	public void onPause() {
		super.onPause();

		if (loadAlbumPicPD != null) {
			loadAlbumPicPD.dismiss();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		mCurlView.onResume();
	}

//	@Override
//	public Object onRetainNonConfigurationInstance() {
//		return mCurlView.getCurrentIndex();
//	}

	private String getDirPath() {
		return Environment.getExternalStorageDirectory()
				+ NativeImageLoader.jihoxUrl + "/.album";
	}

	private String getImagePath(int index) {
		return getDirPath() + "/albumpage" + index + ".jpg";
	}

	/**
	 * Bitmap provider.
	 */
	public class PageProvider implements CurlView.PageProvider {

		Rect targetRect = null;
		private Context context;
		private SoftReference<Drawable> fontSpineDrawable;
		private SoftReference<Drawable> backSpineDrawable;

		public PageProvider(Context context) {
			this.context = context;
		}

		@Override
		public int getPageCount() {
			return bookProject.getBook().getPages().size() / 2;
		}

		DynamicBlockingQueue<Runnable> bqueue = new DynamicBlockingQueue<Runnable>(
				30);
		private ThreadPoolExecutor mImageThreadPool = new ThreadPoolExecutor(2,
				3, 2, TimeUnit.MILLISECONDS, bqueue);
		private boolean firstFlag = true;
		private boolean isCreating = false;
		
		public Bitmap loadBitmapWithCache(int width, int height, int index) {
			Bitmap bitmap = null;

			if (firstFlag) {
				createAlbumImage(width, height);
			} else if (bookProject.getBook().getPages().get(index).isNeedRedraw()) {
				writeOnToSDCard(width, height, index, true);
				mHandler.sendEmptyMessage(LOAD_OK);
			}
			
			bitmap = NativeImageLoader.getInstance()
					.loadNativeImageSyncAndOriginal(getImagePath(index),
							false);
			
			if (bitmap == null) {
				bitmap = writeOnToSDCard(width, height, index, false);
			}
			if (!firstFlag &&index % 2 == 0) {
				preLoadPageImageOnCache(width, height, index);
			}
			if (bitmap.isRecycled()) {
				Bitmap b = writeOnToSDCard(width, height, index, false);
				return b;
			}
			return bitmap;
		}

		private void createAlbumImage(final int width, final int height) {
			if (isCreating){
				return;
			}else{
				isCreating =true;
			}
			DeleteFile(new File(getDirPath()));
			writeOnToSDCard(width, height, 0, true);
			new Thread(new Runnable() {
				@Override
				public void run() {
					int pageSize = bookProject.getBook().getPages().size() - 1;
					int i = 12;
					if (pageSize < i) {
						i = pageSize;
					}
					for (int j=i; j>=0; j--) {
						if (bookProject.getBook().getPages().get(j).isNeedRedraw()){
							writeOnToSDCard(width, height, j, true);
						}
					}
					
					firstFlag = false;
					mHandler.sendEmptyMessage(LOAD_OK);
					
					pageSize = bookProject.getBook().getPages().size();
					for (; i < pageSize; i++) {
						if (bookProject.getBook().getPages().get(i).isNeedRedraw()){
							writeOnToSDCard(width, height, i, true);
						}
					}
					
					isCreating =false;
				}
			}).start();
			
		}

		/**
		 * 递归删除文件
		 * 
		 * @param file
		 *            要删除的根目录
		 */
		public void DeleteFile(File file) {
			if (!file.exists()) {
				return;
			} else {
				if (file.isDirectory()) {
					File[] childFile = file.listFiles();
					if (childFile == null || childFile.length == 0) {
						return;
					}
					for (File f : childFile) {
						if (f.isFile()) {
							f.delete();
						}
					}
				}
			}
		}

		private Bitmap writeOnToSDCard(int width, int height, int index,
				boolean returnNull) {

			String path = getImagePath(index);
			Bitmap pageBitmap = loadBitmap(width, height, index);
			System.gc();
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
				if (isFirstSDRemind) {
					Toast.makeText(
							context,
							getResources().getString(
									R.string.T_NoSD_NoThumbnail),
							Toast.LENGTH_SHORT).show();
					isFirstSDRemind = false;
				}
			} else {
				FileOutputStream fos = null;
				File dir = new File(getDirPath());
				if (!dir.exists() && !dir.isDirectory()) {
					dir.mkdirs();// 创建文件夹
				}

				if (pageBitmap != null && !pageBitmap.isRecycled()) {
					try {
						fos = new FileOutputStream(path);
						pageBitmap
								.compress(Bitmap.CompressFormat.JPEG, 90, fos);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (Exception e) {
						pageBitmap = null;
						e.printStackTrace();
					} finally {
						try {
							fos.flush();
							fos.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
			// 加入MemoryCache内存中
			if (returnNull && pageBitmap != null && !pageBitmap.isRecycled()) {
				NativeImageLoader.getInstance().addBitmapToMemoryCache(path,
						pageBitmap);
				return null;
			}
			return pageBitmap;
		}

		private void preLoadPageImageOnCache(final int width, final int height,
				int index) {
			// TODO Auto-generated method stub
			// 预加载的不对称性
			int[] pagesLRU = { index - 2, index - 1, index + 2, index + 3 };
			for (final int num : pagesLRU) {
				final String imagePath = getImagePath(num);
				// 先检测内存与本地文件中有没有缩略图，如果没有则生成
				if (num >= 0
						&& num < bookProject.getBook().getPages().size()
						&& (NativeImageLoader.getInstance()
								.loadNativeImageSyncAndOriginal(imagePath,
										false) == null || NativeImageLoader
								.getInstance()
								.loadNativeImageSyncAndOriginal(imagePath,
										false).isRecycled())) {
					mImageThreadPool.execute(new Runnable() {
						@Override
						public void run() {
							writeOnToSDCard(width, height, num, true);
						}
					});
				}
			}
		}

		// 加载翻动的压缩图片
		@SuppressWarnings("deprecation")
		private Bitmap loadBitmap(int width, int height, int index) { // TODO:写成异步预加载的，卡
			//float currentScreenRealRatio = 1f;
			float heightRatio = 1f;
			float widthRatio = 1f;
			if (index < bookProject.getBook().getPages().size()) {
				Page currentPage = bookProject.getBook().getPages().get(index);
//				if (currentPage.getType() != 0
//						&& currentPage.getType() != Page.REGULAR) {
//					currentScreenRealRatio = coverPageScreenAndRealRatio * 0.9f;
//				} else {
//					currentScreenRealRatio = innerPageScreenAndRealRatio * 0.9f;
//				}
//				height = (int) (height * 0.9);
//				width = (int) (width * 0.9);
				heightRatio = height/currentPage.getHeight();
				widthRatio = width/currentPage.getWidth();
				
				Bitmap backgroundBitmap = Bitmap.createBitmap(width, height,
						Bitmap.Config.RGB_565);

				backgroundBitmap.eraseColor(0xFFFFFFFF);
				Canvas c = new Canvas(backgroundBitmap);
				// return backgroundBitmap;
				// 背景
				//从对应的Background文件夹中读取背景图片
				if (currentPage.getBackground() != null
						&& !currentPage.getBackground().equals("")) {
					FileInputStream ims;
					try {
						File file = new File(Environment.getExternalStorageDirectory(), ConfigProperties.getTemplatePath() +
				                 templateName + "/" + 
//								"pagecover.jpg");
				                 currentPage.getBackground().trim());
						Log.d("currentPage.getBackground()", currentPage.getBackground() + "");
						Log.d("File", file.getName() + "");
						if (Environment.getExternalStorageState().equals(
				                Environment.MEDIA_MOUNTED)) {
							try {
								ims = new FileInputStream(file);
								Drawable d;
								try {
									d = Drawable.createFromStream(ims, null);
								} catch (OutOfMemoryError e) {
									System.gc();
									System.runFinalization();
									d = Drawable.createFromStream(ims, null);
								} finally {
										ims.close();
								}
								Rect r = new Rect(0, 0, width, height);
								Paint p = new Paint();
								p.setAntiAlias(true);
								p.setColor(0xFFC0C0C0);
								c.drawRect(r, p);
								d.setBounds(r);
								d.draw(c);
								d.setCallback(null);
								BitmapDrawable bd = (BitmapDrawable) d;
								if (!bd.getBitmap().isRecycled()) {
									bd.getBitmap().recycle();
								}
								
							} catch (FileNotFoundException e) {
//								Toast.makeText(CurlActivity.this, getResources().getString(R.string.T_Read_Template_Error),
//				                     Toast.LENGTH_SHORT).show();
								fileHandler.sendEmptyMessage(1);
								e.printStackTrace();
							}
				         }else {
				        	 
				         // 此时SDcard不存在或者不能进行读写操作的
				        	 fileHandler.sendEmptyMessage(2);
//				         Toast.makeText(CurlActivity.this,
//				                 getResources().getString(R.string.T_No_SDCard), Toast.LENGTH_SHORT).show();
						 }
					} catch (IOException e) {
						fileHandler.sendEmptyMessage(3);
					}
				}
						
				// 图片s
				if (currentPage.getPictures() != null
						&& currentPage.getPictures().size() > 0) {
					for (PagePicture pagePicture : currentPage.getPictures()) {
						if (pagePicture.getImage() != null
								&& (pagePicture.getImage().getPath() != null && !pagePicture
										.getImage().getPath().equals(""))) {
							String path = pagePicture.getImage().getPath();
							// mPoint 这里用作记录所需要的图片大小
							Point mPoint = new Point(width * 2, height * 2);
							Bitmap photo = null;
							Bitmap copyphoto = null;
							BitmapDrawable d = null;
							if (pagePicture.isClipart()) {
								// 图片加载失败
								// InputStream ims;
								// d = Drawable.createFromStream(ims, null);
								BitmapFactory.Options options = new BitmapFactory.Options();
								options.inPreferredConfig = Config.RGB_565;
								photo = PictureUtil
										.getThumbFromSDcard(
												getApplicationContext(),
												ConfigProperties.getTemplatePath() +
								                templateName + "/" +
												path.trim(),
												(int) (pagePicture.getHolder()
														.getWidth() * widthRatio),
												(int) (pagePicture.getHolder()
														.getHeight() * heightRatio));
								d = new BitmapDrawable(photo);

							} else {
								photo = NativeImageLoader.getInstance()
										.loadNativeImageSync(path.trim(),
												mPoint, false);
								// 加载出错 绘制提醒字体
								if (photo == null) {
									// Log.d("CurlActivity",
									// "lines 875 photo is null index = " +
									// index);
									photo = Bitmap.createBitmap(mPoint.x,
											mPoint.y, Config.RGB_565);
									photo.eraseColor(Color.WHITE);
									Canvas pc = new Canvas(photo);
									Paint paint = new Paint(
											Paint.ANTI_ALIAS_FLAG);
									paint.setAntiAlias(true);
									paint.setStrokeWidth(3);
									// TODO: 字体大小有待调查
									paint.setTextSize((float) (80));// 设置字体大小

									String text = getResources().getString(
											R.string.No_Picture_Warning);
									paint.setColor(Color.RED);
									paint.setTextAlign(Paint.Align.CENTER);
									pc.drawText(text, mPoint.x / 2 - 10,
											mPoint.y / 2, paint);
									pc.save();
								}
								int photoHeight = photo.getHeight();
								int photoWidth = photo.getWidth();
								
								//计算移动后我们算得的照片宽高
								int mpicWidth =-(int)(pagePicture.getImage().getX()*photoWidth/pagePicture.getImage().getWidth())
										+(int) (pagePicture.getHolder().getWidth()*photoWidth/pagePicture.getImage().getWidth());
								int mpicHeight =-(int)(pagePicture.getImage().getY()*photoHeight/pagePicture.getImage().getHeight())
										+(int) (pagePicture.getHolder().getHeight()*photoHeight/pagePicture.getImage().getHeight());
								//算得的照片宽高比实际照片的大，则移动位置为照片实际位置减去末端位置，如果比实际的小就使用我们算出的位置
								int mpicX1;
								if(photoWidth<mpicWidth){
									mpicX1 = photoWidth - (int)(pagePicture.getHolder().getWidth()*photoWidth/pagePicture.getImage().getWidth());
								}else{
									mpicX1 = -(int)(pagePicture.getImage().getX()*photoWidth/pagePicture.getImage().getWidth());
								}
								int mpicY1;
								if(photoHeight<mpicHeight){
									mpicY1 = photoHeight - (int)(pagePicture.getHolder().getHeight()*photoHeight/pagePicture.getImage().getHeight());
								}else{
									mpicY1 = -(int)(pagePicture.getImage().getY()*photoHeight/pagePicture.getImage().getHeight());
								}
								
								copyphoto = Bitmap.createBitmap(photo, 
										mpicX1,
										mpicY1,
										(int) (pagePicture.getHolder().getWidth()*photoWidth/pagePicture.getImage().getWidth()), 
										(int) (pagePicture.getHolder().getHeight()*photoHeight/pagePicture.getImage().getHeight())).copy(Bitmap.Config.RGB_565, true);
								pagePicture.getImage().setQualified(true);							
								if (copyphoto == null) {
									d = new BitmapDrawable(photo);
								} else {
									d = new BitmapDrawable(copyphoto);
								}
							}

							float pointX = pagePicture.getHolder().getX()
									* widthRatio;
							float pointY = pagePicture.getHolder().getY()
									* heightRatio;
							
							float pointX1 = pointX
									+ pagePicture.getHolder().getWidth()
									* widthRatio;
							float pointY1 = pointY
									+ pagePicture.getHolder().getHeight()
									* heightRatio;
							Rect r = new Rect(Math.round(pointX),
									Math.round(pointY), Math.round(pointX1),
									Math.round(pointY1));
							Paint p = new Paint();
							p.setAlpha(0);
							c.drawRect(r, p);
							p.setAntiAlias(true);
							p.setFilterBitmap(true);
							d.setBounds(r);
							d.setFilterBitmap(true);
							try{
								d.draw(c);
							}catch(Exception e){
								
							}
							
							c.setDrawFilter(new PaintFlagsDrawFilter(0,
									Paint.ANTI_ALIAS_FLAG
											| Paint.FILTER_BITMAP_FLAG));
							c.save();
							
							if (pagePicture.getHolder().getMaskPath() != null && !pagePicture
									.getHolder().getMaskPath().equals("")) {
								Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
								paint.setFilterBitmap(true);
								paint.setAntiAlias(true);
								Bitmap maskBitmap = PictureUtil
										.getThumbFromSDcard(
												getApplicationContext(),
												ConfigProperties.getTemplatePath() +
								                templateName  + "/" + pagePicture
												.getHolder().getMaskPath(),
												(int) (pagePicture.getHolder()
														.getWidth() * widthRatio),
												(int) (pagePicture.getHolder()
														.getHeight() * heightRatio));

								c.setDrawFilter(new PaintFlagsDrawFilter(0,
										Paint.ANTI_ALIAS_FLAG
												| Paint.FILTER_BITMAP_FLAG));
			
								if (maskBitmap!=null && !maskBitmap.isRecycled()){
									c.drawBitmap(maskBitmap, null, r, paint);
									maskBitmap.recycle();
								}
							}
							
							if (!pagePicture.isClipart()) {
								// 图片像素不足给予提示
								if (!PictureUtil.isSuitablePicture(
										bookProject.getBook().getProduct().getDpiOfPicture(),pagePicture)) {
									pagePicture.getImage().setQualified(false);
									Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
									paint.setFilterBitmap(true);
									paint.setAntiAlias(true);
									if (pagePicture.getWarnningImage()!=null && pagePicture.getWarnningImage().getPath()!=null 
											&& !pagePicture.getWarnningImage().getPath().isEmpty()){
										Bitmap promptBitmap = PictureUtil
												.getThumbFromSDcard(
														getApplicationContext(),
														ConfigProperties.getTemplatePath() +
										                templateName  + "/" + pagePicture
														.getWarnningImage().getPath());
										c.setDrawFilter(new PaintFlagsDrawFilter(0,
												Paint.ANTI_ALIAS_FLAG
														| Paint.FILTER_BITMAP_FLAG));
										//右下角为照片框短边的1/5
										float X1= pointX + pagePicture.getWarnningImage().getX()*widthRatio; 
										float Y1= pointY + pagePicture.getWarnningImage().getY()*heightRatio; 
										float X2= X1 + pagePicture.getWarnningImage().getWidth()*widthRatio; 
										float Y2= Y1 + pagePicture.getWarnningImage().getHeight()*heightRatio; 
										
										if (promptBitmap != null
												&& !promptBitmap.isRecycled()) {
											c.drawBitmap(promptBitmap, null, new Rect(Math.round(X1),
													Math.round(Y1),Math.round(X2),
													Math.round(Y2)), paint);
											promptBitmap.recycle();
										}
									}else{
										Bitmap promptBitmap = PictureUtil
												.readBitMap(
														getApplicationContext(),
														R.drawable.warnning);
		
										c.setDrawFilter(new PaintFlagsDrawFilter(0,
												Paint.ANTI_ALIAS_FLAG
														| Paint.FILTER_BITMAP_FLAG));
										//右下角为照片框短边的1/5
										float X1; 
										float Y1;
										if(pagePicture.getHolder().getWidth()
												* widthRatio>=pagePicture.getHolder().getHeight()
												* heightRatio){
											X1 = pointX + pagePicture.getHolder().getHeight()* heightRatio*0.2f;
											Y1 = pointY + pagePicture.getHolder().getHeight()* heightRatio*0.2f;
										}else{
											X1 = pointX + pagePicture.getHolder().getWidth()* widthRatio*0.2f;
											Y1 = pointY + pagePicture.getHolder().getWidth()* widthRatio*0.2f;
										}
										
										c.drawBitmap(promptBitmap, null, new Rect(Math.round(pointX+5),
												Math.round(pointY+5),Math.round(X1),
												Math.round(Y1)), paint);
										if (promptBitmap != null
												&& !promptBitmap.isRecycled()) {
											promptBitmap.recycle();
										}
									}
								}
							}
							if (copyphoto != null && !copyphoto.isRecycled()) {
								copyphoto.recycle();
							}

							if (pagePicture.isClipart() && photo != null
									&& !photo.isRecycled()) {
								photo.recycle();
							}
							d.setCallback(null);
							if (d!=null && d.getBitmap()!=null && !d.getBitmap().isRecycled()) {
								d.getBitmap().recycle();
							}
							
							photo = null;
						}
					}
				}
				// captions
				if (currentPage.getCaptions() != null
						&& currentPage.getCaptions().size() > 0) {
					for (Caption caption : currentPage.getCaptions()) {
						float pointX = caption.getX() * widthRatio;
						float pointY = caption.getY() * heightRatio;
						float pointX1 = pointX + caption.getWidth()
								* widthRatio;
						float pointY1 = pointY + caption.getHeight()
								* heightRatio;
						targetRect = new Rect(Math.round(pointX),
								Math.round(pointY), Math.round(pointX1),
								Math.round(pointY1));

						Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
						paint.setAntiAlias(true);
						paint.setStrokeWidth(3);
						
						paint.setTextSize((float) (caption.getFont().getSize()
								* widthRatio / 2.85));// 设置字体大小

						paint.setTypeface(typeface);// 设置字体类型
						FontMetricsInt fontMetrics = paint.getFontMetricsInt();
						int baseline = targetRect.top
								+ (targetRect.bottom - targetRect.top
										- fontMetrics.bottom + fontMetrics.top)
								/ 2 - fontMetrics.top;

						String text = caption.getText();
						if (caption.isShowTempText()){
							text = caption.getTempText();
						}
						if (text == null || text.isEmpty()) {
							text = caption.getPlaceHolder();
							if (text == null) {
								text = "";
							} else {
								if (!text.isEmpty()) {
									paint.setColor(Color.LTGRAY);
								}
							}
						} else {
							if (!currentPage.isBackCover()) {
//								text = getDrawTextString(text, paint, pointX1
//										- pointX);
							}
							paint.setColor(Color.rgb(caption.getColor()
									.getRed(), caption.getColor().getGreen(), 
									caption.getColor().getBlue()));
						}
						if (caption.getDocAlign() == Caption.ALIGN_RIGHT) {
							paint.setTextAlign(Paint.Align.RIGHT);
							c.drawText(text, targetRect.right, baseline, paint);
						} else if (caption.getDocAlign() == Caption.ALIGN_LEFT) {
							paint.setTextAlign(Paint.Align.LEFT);
							c.drawText(text, targetRect.left, baseline, paint);
						} else {
							paint.setTextAlign(Paint.Align.CENTER);
							c.drawText(text, targetRect.centerX(), baseline,
									paint);
						}
					}
				}
				// 正反面有不同的处理，1.反面的需要对称。2.所以反面的innerspine贴图位置正好要相反
				Rect spine;
				Paint p = new Paint();
				p.setColor(00000000);
				int spineWidth = (int) (width * 0.02);
				int spineHeight = (int) (height * 0.02);
				if (index % 2 != 0) {
					Drawable spineDrawable = null;
					if (backSpineDrawable == null) {
						spineDrawable = PictureUtil.getDrawableFromAssetsFile(
								getApplicationContext(), "album_spine_back.png");
						backSpineDrawable = new SoftReference<Drawable>(
								spineDrawable);
					} else {
						spineDrawable = backSpineDrawable.get();
						if (spineDrawable == null) {
							spineDrawable = PictureUtil
									.getDrawableFromAssetsFile(
											getApplicationContext(),
											"album_spine_back.png");
							backSpineDrawable = new SoftReference<Drawable>(
									spineDrawable);
						}
					}

					if (bookProject.getBook().getProduct().getCategory() == 1) {
						if (currentPage.getType() == Page.REGULAR) {
							spine = new Rect();
							spine.left = width - spineWidth;
							spine.top = 0;
							spine.right = width;
							spine.bottom = height;
							c.drawRect(spine, p);
							spineDrawable.setBounds(spine);
							spineDrawable.draw(c);
						}
						Matrix matrix = new Matrix();
						float[] values = { -1f, 0.0f, 0.0f, 0.0f, 1f, 0.0f,
								0.0f, 0.0f, 1.0f };
						matrix.setValues(values);
						dstbmp = Bitmap.createBitmap(backgroundBitmap, 0, 0,
								backgroundBitmap.getWidth(),
								backgroundBitmap.getHeight(), matrix, true);
						// 回收内存
						backgroundBitmap.recycle();
						currentPage.setNeedRedraw(false);
						return dstbmp;
					} else {
//						spine = new Rect();
//						spine.left = 0;
//						spine.top = 0;
//						spine.right = width;
//						spine.bottom = spineHeight;
//						c.drawRect(spine, p);
//						spineDrawable.setBounds(spine);
//						spineDrawable.draw(c);

						Matrix matrix = new Matrix();
						float[] values = { -1f, 0.0f, 0.0f, 0.0f, 1f, 0.0f,
								0.0f, 0.0f, 1.0f };
						matrix.setValues(values);
						dstbmp = Bitmap.createBitmap(backgroundBitmap, 0, 0,
								backgroundBitmap.getWidth(),
								backgroundBitmap.getHeight(), matrix, true);
						// 回收内存
						backgroundBitmap.recycle();
						currentPage.setNeedRedraw(false);
						return dstbmp;
					}
				} else {
					Drawable spineDrawable = null;
					if (fontSpineDrawable == null) {
						spineDrawable = PictureUtil.getDrawableFromAssetsFile(
								getApplicationContext(), "album_spine_front.png");
						fontSpineDrawable = new SoftReference<Drawable>(
								spineDrawable);
					} else {
						spineDrawable = fontSpineDrawable.get();
						if (spineDrawable == null) {
							spineDrawable = PictureUtil
									.getDrawableFromAssetsFile(
											getApplicationContext(),
											"album_spine_front.png");
							fontSpineDrawable = new SoftReference<Drawable>(
									spineDrawable);
						}
					}

					if (bookProject.getBook().getProduct().getCategory() == 1) {
						if (currentPage.getType() == Page.REGULAR) {
							spine = new Rect();
							spine.left = 0;
							spine.top = 0;
							spine.right = spineWidth;
							spine.bottom = height;
							c.drawRect(spine, p);
							spineDrawable.setBounds(spine);
							spineDrawable.draw(c);
						}
						currentPage.setNeedRedraw(false);
						return backgroundBitmap;
					} else {
//						spine = new Rect();
//						spine.left = 0;
//						spine.top = 0;
//						spine.right = width;
//						spine.bottom = spineHeight;
//						c.drawRect(spine, p);
//						spineDrawable.setBounds(spine);
//						spineDrawable.draw(c);
//						currentPage.setNeedRedraw(false);
						return backgroundBitmap;
					}
				}
				
			} else {
				return Bitmap
						.createBitmap(width, height, Bitmap.Config.RGB_565);
			}
		}
		
		private void drawText(Canvas c,Caption caption,float currentScreenRealRatio,Rect target){
			Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
			paint.setAntiAlias(true);
			paint.setStrokeWidth(3);
			
			paint.setTextSize((float) (caption.getFont().getSize()
					* currentScreenRealRatio / 2.85));// 设置字体大小
			// android默认字体有：monospace sans serif
			paint.setTypeface(typeface);// 设置字体类型
			FontMetricsInt fontMetrics = paint.getFontMetricsInt();
			int baseline = target.top
					+ (target.bottom - target.top
							- fontMetrics.bottom + fontMetrics.top)
					/ 2 - fontMetrics.top;

			String text = "请在此处添加文字";
			
			paint.setColor(Color.LTGRAY);
			
			if (caption.getDocAlign() == Caption.ALIGN_RIGHT) {
				paint.setTextAlign(Paint.Align.RIGHT);
				c.drawText(text, target.right, baseline, paint);
			} else if (caption.getDocAlign() == Caption.ALIGN_LEFT) {
				paint.setTextAlign(Paint.Align.LEFT);
				c.drawText(text, target.left, baseline, paint);
			} else {
				paint.setTextAlign(Paint.Align.CENTER);
				c.drawText(text, target.centerX(), baseline,
						paint);
			}
		}

		@SuppressLint("ResourceAsColor") @Override
		public void updatePage(CurlPage page, int width, int height, int index) {
			height = (int) (height * 0.9);
			width = (int) (width * 0.9);
			if(imageHeight == 0 && imageWidth == 0){
				imageHeight = height;
				imageWidth = width;
			}
			Bitmap copyfront = null;
			Bitmap copyback = null;
			Canvas frontCanvas = null;
			Canvas backCanvas = null;
			front = loadBitmapWithCache(width, height, index * 2);
			back = loadBitmapWithCache(width, height, index * 2 + 1);
			// 判断是否是编辑状态
			if (isEditState) {
				
				Page currentPage = bookProject.getBook().getPages().get(index);
				
				
				
				List<Rect> front_rects = getCaptionRect(width,height,index * 2);
				List<Rect> back_rects = getCaptionRect(width,height,index * 2 + 1);
				
				List<Rect> front_pic_rects = getPictureRect(index * 2);
				List<Rect> back_pic_rects = getPictureRect(index * 2 + 1);
				
				Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
				mPaint.setColor(CurlActivity.this.getResources().getColor(
						R.color.darkgrey));
				mPaint.setStyle(Style.STROKE);
				if (front_rects != null && front_rects.size() > 0) {
					copyfront = front.copy(Config.RGB_565, true);
					frontCanvas = new Canvas(copyfront);
					for (int i=0;i<front_rects.size();i++) {
						Caption caption = bookProject.getBook().getPages().get(index*2).getCaptions().get(i);
						if(caption.isEditable()){
							frontCanvas.drawRect(front_rects.get(i), mPaint);
							if (((caption.getText()==null || caption.getText().isEmpty())&& !caption.isShowTempText())
									||((caption.getTempText()==null||caption.getTempText().isEmpty())&& caption.isShowTempText())){
								drawText(frontCanvas,caption,width/currentPage.getWidth(),front_rects.get(i));
							}
						}
					}
					if (mPageNum  == index * 2){
						mPaint.setColor(CurlActivity.this.getResources().getColor(R.color.red));
						frontCanvas.drawRect(front_pic_rects.get(mPictureNum), mPaint);
					}
					frontCanvas.save();
					page.setTexture(copyfront, CurlPage.SIDE_FRONT);
				} else {
					page.setTexture(front, CurlPage.SIDE_FRONT);
				}
				
				
				if (back_rects != null && back_rects.size() > 0) {
					copyback = back.copy(Config.RGB_565, true);
					Matrix matrix = new Matrix();
					float[] values = { -1f, 0.0f, 0.0f, 0.0f, 1f, 0.0f,
							0.0f, 0.0f, 1.0f };
					matrix.setValues(values);
					copyback = Bitmap.createBitmap(copyback, 0, 0,
							copyback.getWidth(),
							copyback.getHeight(), matrix, true);
					
					backCanvas = new Canvas(copyback);

					mPaint.setColor(CurlActivity.this.getResources().getColor(
							R.color.darkgrey));
					for (int i=0;i<back_rects.size();i++) {
						Caption caption = bookProject.getBook().getPages().get(index*2+1).getCaptions().get(i);
						if(bookProject.getBook().getPages().get(index*2+1).getCaptions().get(i).isEditable()){
							backCanvas.drawRect(back_rects.get(i), mPaint);
							if ((caption.getText().isEmpty()&& !caption.isShowTempText())||(caption.getTempText().isEmpty()&& caption.isShowTempText())){
								drawText(backCanvas,caption,width/currentPage.getWidth(),back_rects.get(i));
							}
						}
					}
					if (mPageNum  == index * 2+1){
						mPaint.setColor(CurlActivity.this.getResources().getColor(R.color.red));
						backCanvas.drawRect(back_pic_rects.get(mPictureNum), mPaint);
					}
					copyback = Bitmap.createBitmap(copyback, 0, 0,
							copyback.getWidth(),
							copyback.getHeight(), matrix, true);
					
					backCanvas.save();
					page.setTexture(copyback, CurlPage.SIDE_BACK);
				} else {
					page.setTexture(back, CurlPage.SIDE_BACK);
				}
				
				
			} else {
				page.setTexture(front, CurlPage.SIDE_FRONT);
				page.setTexture(back, CurlPage.SIDE_BACK);
			}
			
		}
	}

	private static String getDrawTextString(String str, Paint paint, float width) {
		String ret = str;
		int textWidth = 0;
		if (str != null && str.length() > 0) {
			int len = str.length();
			float[] widths = new float[len];
			paint.getTextWidths(str, widths);
			for (int j = 0; j < len; j++) {
				textWidth += (int) Math.ceil(widths[j]);
			}
		}

		if (textWidth > width) {
			if (ret.endsWith("…")) {
				ret = ret.substring(0, ret.length() - 3) + "…";
			} else {
				ret = ret.substring(0, ret.length() - 2) + "…";
			}

			return getDrawTextString(ret, paint, width);
		}

		return ret;
	}

	/**
	 * CurlView size changed observer.
	 */
	private class SizeChangedObserver implements CurlView.SizeChangedObserver {
		@Override
		public void onSizeChanged(int w, int h) {
			curlViewMarginLeftOrRight = -1;
			curlViewMarginTop = 0.16f;
			if (bookProject != null
					&& bookProject.getBook().getProduct().getCategory() == 2) {
				curlViewMarginTop = 0.11f;
				curlViewMarginBottom = .11f;
				if (changedSizeForCalendar) {
					return;
				} else {
					changedSizeForCalendar = true;
				}

			} else {
				curlViewMarginBottom = .13f;
				if (changedSizeForPhotoBook) {
					return;
				} else {
					changedSizeForPhotoBook = true;
				}

			}
			while (curlViewMarginLeftOrRight <= 0) {// 根据相册的宽高比来寻找上下边距，再确定左右边距。
				curlViewMarginTop += 0.01f;
				curlViewMarginBottom += 0.01f;
				if (bookProject != null
						&& bookProject.getBook().getProduct().getCategory() == 2) {
					innerPageScreenAndRealRatio = mCurlView.getHeight()
							* (1f - curlViewMarginTop - curlViewMarginBottom)
							/ 2f
							/ bookProject.getBook().getPages().get(0).getHeight();
					coverPageScreenAndRealRatio = mCurlView.getHeight()// 封面会稍微大一些
							* (1f - curlViewMarginTop - curlViewMarginBottom)
							/ 2f
							/ bookProject.getBook().getPages().get(0)
									.getHeight();
					curlViewMarginLeftOrRight = (1f - bookProject.getBook().getPages().get(0).getWidth()
							* innerPageScreenAndRealRatio
							/ mCurlView.getWidth()) / 2f;
				} else {
					innerPageScreenAndRealRatio = mCurlView.getHeight()
							* (1 - curlViewMarginTop - curlViewMarginBottom)
							/ bookProject.getBook().getPages().get(0).getHeight();
					coverPageScreenAndRealRatio = mCurlView.getHeight()// 封面会稍微大一些
							* (1 - curlViewMarginTop - curlViewMarginBottom)
							/ bookProject.getBook().getPages().get(0)
									.getHeight();
					curlViewMarginLeftOrRight = 0.5f
							- bookProject.getBook().getPages().get(0).getWidth()
							* innerPageScreenAndRealRatio
							/ mCurlView.getWidth();
				}
			}
			mCurlView.setMargins(curlViewMarginLeftOrRight, curlViewMarginTop,
					curlViewMarginLeftOrRight, curlViewMarginBottom);

			WindowManager wm = CurlActivity.this.getWindowManager();
			int screenWidth = wm.getDefaultDisplay().getWidth();
			int screenHeight = wm.getDefaultDisplay().getHeight();
			int padding = 80;
			int changeCaptionLayoutSide;
			int changeCaptionLayoutMarginTop;
			int changeCaptionLayoutMarginBottom;
			int changeCaptionLayoutMarginRight;
			int changeCaptionLayoutMarginLeft;

			LinearLayout changeCaptionLayout = (LinearLayout) findViewById(R.id.change_caption_layout);
			RelativeLayout titleBarRelativeLayout = (RelativeLayout) findViewById(R.id.titlebar);

			FrameLayout.LayoutParams lp = null;
			if (bookProject.getBook().getProduct().getCategory() == 1) {
				changeCaptionLayoutSide = (int) (screenHeight * (1f - curlViewMarginTop - curlViewMarginBottom))
						- 2 * padding;
				changeCaptionLayoutMarginTop = (int) (screenHeight * curlViewMarginTop)
						+ padding / 2;
				changeCaptionLayoutMarginBottom = (int) (screenHeight * curlViewMarginBottom)
						+ padding * 3 / 2;
				changeCaptionLayoutMarginRight = (int) (screenWidth / 2) + 2
						* padding;
				changeCaptionLayoutMarginLeft = (int) (screenWidth / 2 - changeCaptionLayoutSide)
						- 2 * padding;
				lp = new FrameLayout.LayoutParams(changeCaptionLayoutSide
						+ padding, changeCaptionLayoutSide + padding);
				lp.setMargins(changeCaptionLayoutMarginLeft + padding - 15,
						changeCaptionLayoutMarginTop - 10,
						changeCaptionLayoutMarginRight + 15,
						changeCaptionLayoutMarginBottom - padding + 10);
			} else {
				int viewRectHeight = (int) (screenHeight * (1 - curlViewMarginBottom - curlViewMarginTop));
				int viewRectWidth = (int) (screenWidth * (1 - 2 * curlViewMarginLeftOrRight));
				changeCaptionLayoutMarginBottom = (int) (screenHeight / 2 + CurlRenderer.moveYDis
						/ 2 * viewRectHeight)
						+ padding;
				changeCaptionLayoutMarginTop = screenHeight - viewRectHeight
						/ 2 - changeCaptionLayoutMarginBottom + 2 * padding;
				changeCaptionLayoutMarginRight = changeCaptionLayoutMarginLeft = (screenWidth - viewRectWidth)
						/ 2 + padding;
				lp = new FrameLayout.LayoutParams(viewRectWidth - 2 * padding,
						viewRectHeight / 2 - 2 * padding);
				lp.setMargins(changeCaptionLayoutMarginLeft,
						changeCaptionLayoutMarginTop,
						changeCaptionLayoutMarginRight,
						changeCaptionLayoutMarginBottom);

//				LinearLayout spine_loop_top_layout = (LinearLayout) findViewById(R.id.spine_loop_top_layout);
//				LinearLayout spine_loop_bottom_layout = (LinearLayout) findViewById(R.id.spine_loop_bottom_layout);
				// LinearLayout calendar_bottom_layout = (LinearLayout)
				// findViewById(R.id.calendar_bottom_layout);

				float ratio = 1.057f;
				FrameLayout.LayoutParams spine_loop_top_lp = new FrameLayout.LayoutParams(
						(int) (viewRectWidth / ratio),
						(int) (viewRectHeight * 0.011));
				FrameLayout.LayoutParams spine_loop_bottom_lp = new FrameLayout.LayoutParams(
						(int) (viewRectWidth / ratio),
						(int) (viewRectHeight * 0.011));
				// FrameLayout.LayoutParams calendar_bottom_lp = new
				// FrameLayout.LayoutParams((int)(viewRectWidth/ratio),(int)
				// (viewRectHeight/2/ratio*1.1));

				int left = changeCaptionLayoutMarginLeft - padding
						+ (viewRectWidth - (int) (viewRectWidth / ratio)) / 2;
				int top = screenHeight
						- (int) (screenHeight / 2 + CurlRenderer.moveYDis / 2
								* viewRectHeight)
						- (int) (viewRectHeight * 0.011) + 1;
				int right = changeCaptionLayoutMarginRight - padding
						+ (viewRectWidth - (int) (viewRectWidth / ratio)) / 2;
				int bottom = (int) (screenHeight / 2 + CurlRenderer.moveYDis
						/ 2 * viewRectHeight) - 1;
				spine_loop_top_lp.setMargins(left, top, right, bottom);
				//spine_loop_top_layout.setLayoutParams(spine_loop_top_lp);

				top = screenHeight
						- (int) (screenHeight / 2 + CurlRenderer.moveYDis / 2
								* viewRectHeight) - 1;
				bottom = (int) (screenHeight / 2 + CurlRenderer.moveYDis / 2
						* viewRectHeight)
						- (int) (viewRectHeight * 0.011) + 1;

				spine_loop_bottom_lp.setMargins(left, top, right, bottom);
				//spine_loop_bottom_layout.setLayoutParams(spine_loop_bottom_lp);

				top = screenHeight / 2;
				bottom = (int) (screenHeight / 2 - viewRectHeight / ratio / 2
						* 1.1);
				// calendar_bottom_lp.setMargins(left, top, right, bottom);
				// calendar_bottom_layout.setLayoutParams(calendar_bottom_lp);
			}

			changeCaptionLayout.setLayoutParams(lp);
			int relativeLayoutHeight = (int) (screenHeight * curlViewMarginTop);
			if (relativeLayoutHeight <= 0) {
				relativeLayoutHeight = DensityUtil
						.dip2px(CurlActivity.this, 60);
			}
			RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, relativeLayoutHeight);
			titleBarRelativeLayout.setLayoutParams(rlp);

		}
	}

	// 处理startActivityForResult的回调函数
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {		

		if(requestCode == EDIE_SINGLE_PAGE && resultCode == RESULT_OK){
			bookProject = (BookProject) data.getSerializableExtra("bookProject");
			MyApplication.getInstance().setBookProject(bookProject);
			orignal_project.getBook().getPages().get(mPageNum).setNeedRedraw(true);
			mCurlView.releaseMemory();
			mCurlView.setFirstMoveFlag(true);
			mCurlView.setCurrentIndex(mCurlView.getCurrentIndex());
		}
		// resultCode : 1 保存， 0 取消
		if (addPAgeRequestCode==requestCode){
			if (resultCode == 1) {
				mCurlView.onPause();
				mCurlView.releaseMemory();
				pageProvider = new PageProvider(this);
				mCurlView.setPageProvider(pageProvider);
				loadImageProgressBar();
			}
		}else{
			if (resultCode == 1) {
				// 添加文字
				Bundle bundle = data.getExtras();
				currentIndex = bundle.getInt("CurrentIndex");
				mCurlView.onPause();
				mCurlView.releaseMemory();
				mCurlView.setFirstMoveFlag(true);
				mCurlView.setCurrentIndex(currentIndex);
				
			}
		}
	}

	// 返回每个页面中的文字框
	private List<Rect> getCaptionRect(int width, int height,int index) {

		List<Rect> rects = new ArrayList<Rect>();
		Page currentPage = bookProject.getBook().getPages().get(index);
		List<Caption> captions = currentPage.getCaptions();
		
		float heightRatio = height/currentPage.getHeight();
		float widthRatio = width/currentPage.getWidth();
		
		if (captions != null && captions.size() > 0) {
			for (Caption caption : captions) {
				if (!caption.isEditable()){
					continue;
				}
				float pointX = caption.getX()* widthRatio;
				float pointY = caption.getY()* heightRatio;
				float pointX1 = pointX + caption.getWidth()
						* widthRatio;
				float pointY1 = pointY + caption.getHeight()
						* heightRatio;
				Rect rect = new Rect(Math.round(pointX), Math.round(pointY),
						Math.round(pointX1), Math.round(pointY1));
				rects.add(rect);
			}
			return rects;
		}
		return null;
	}
	
	// 返回每个页面中的文字框
	private List<Rect> getCaptionRect(int index) {
		float currentScreenRealRatio = 1f;
		List<Rect> rects = new ArrayList<Rect>();
		Page currentPage = bookProject.getBook().getPages().get(index);
		List<Caption> captions = currentPage.getCaptions();
		if (currentPage.getType() != 0 && currentPage.getType() != Page.REGULAR) {
			currentScreenRealRatio = coverPageScreenAndRealRatio * 0.9f;
		} else {
			currentScreenRealRatio = innerPageScreenAndRealRatio * 0.9f;
		}
		if (captions != null && captions.size() > 0) {
			for (Caption caption : captions) {
				if (!caption.isEditable()){
					continue;
				}
				float pointX = caption.getX()* currentScreenRealRatio;
				float pointY = caption.getY()* currentScreenRealRatio;
				float pointX1 = pointX + caption.getWidth()
						* currentScreenRealRatio;
				float pointY1 = pointY + caption.getHeight()
						* currentScreenRealRatio;
				Rect rect = new Rect(Math.round(pointX), Math.round(pointY),
						Math.round(pointX1), Math.round(pointY1));
				rects.add(rect);
			}
			return rects;
		}
		return null;
	}
	
	// 返回每个页面中的照片框
	private List<Rect> getPictureRect(int index) {
		float currentScreenRealRatio = 1f;
		List<Rect> rects = new ArrayList<Rect>();
		Page currentPage = bookProject.getBook().getPages().get(index);
		List<PagePicture> pictures = currentPage.getPictures();
		if (currentPage.getType() != 0 && currentPage.getType() != Page.REGULAR) {
			currentScreenRealRatio = coverPageScreenAndRealRatio * 0.9f;
		} else {
			currentScreenRealRatio = innerPageScreenAndRealRatio * 0.9f;
		}
		if (pictures != null && pictures.size() > 0) {
			for (PagePicture picture : pictures) {
				float pointX = picture.getHolder().getX()* currentScreenRealRatio;
				float pointY = picture.getHolder().getY()* currentScreenRealRatio;
				float pointX1 = pointX + picture.getHolder().getWidth()
						* currentScreenRealRatio;
				float pointY1 = pointY + picture.getHolder().getHeight()
						* currentScreenRealRatio;
				Rect rect = new Rect(Math.round(pointX), Math.round(pointY),
						Math.round(pointX1), Math.round(pointY1));
				rects.add(rect);
			}
			return rects;
		}
		return null;
	}
	
}